//
//  Air_BannerCollectionCell.swift
//  旅航ios
//
//  Created by tulip on 2021/4/26.
///Users/tulip/Desktop/旅航/旅航ios/旅航ios/首页/机票/AirplaneVC.swift

import UIKit
import JXBanner
import SwiftyJSON
import HandyJSON
class Air_BannerCollectionCell: UICollectionViewCell,JXBannerDataSource,JXBannerDelegate,UIGestureRecognizerDelegate,MSSCalendarViewControllerDelegate {
    
    var propData:[JSON]?
    
    var noti:String = ""
    
    var calenArr:Array<Any> = []

    var banner:JXBanner!
    @IBOutlet weak var bannerBox: UIView!
    @IBOutlet weak var postBtn: UIButton!
    
    @IBOutlet weak var notiBt: UIButton!
    @IBOutlet weak var exchangeImg: UIImageView!
    @IBOutlet weak var cangweiBtn: UIButton!
    @IBOutlet weak var kidBtn: UIButton!
    @IBOutlet weak var yingErBtn: UIButton!
    var childType=0
    var cabinArr:Array<Int>=[1,2]
    var go_Time:String!
    var back_Time:String!
    var departCityCode:String="CTU"
    var arriveCityCode:String="PVG"
    
    @IBOutlet weak var wfBtn: UIButton!
    @IBOutlet weak var dcBtn: UIButton!
    
  
    @IBOutlet weak var goTime: UILabel!
    @IBOutlet weak var address_to: UILabel!
    @IBOutlet weak var address_from: UILabel!
    @IBOutlet weak var box: UIImageView!
    
    @IBOutlet weak var backTime: UIButton!
    @IBOutlet weak var collect: UICollectionView!
    var pageControl:WEIPageControl!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        postBtn=gradientColor(colo1: "ff8e4a", colo2: "ff6635", view: postBtn, width: SCREEN_WIDTH-64) as? UIButton
        postBtn.layer.cornerRadius=25
        postBtn.layer.masksToBounds=true
        
        
        //获取日期格式化对象
        let dateFormatter=DateFormatter.init()
        dateFormatter.dateFormat="yyyy-MM-dd"
        dateFormatter.locale=Locale(identifier: "zh_CN")
        //记住当前时间戳
        var times = Date.init().timeStamp
        times = times + 5*60
        //获取当前完整日期
        let today=dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(times)))
        go_Time=today
        back_Time=today
        
//        notiBt.setTitle(noti, for: .normal)
       
        //获取当天日期号
        let day=today.components(separatedBy: "-")[1] + "月" + today.components(separatedBy: "-")[2] + "日"
        goTime.text=day
        backTime.setTitle(day, for: .normal)
        
        
        
        banner=JXBanner.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 209))
        banner.delegate = self
        banner.dataSource = self
        bannerBox.addSubview(banner)
        
      
        
        
        
        //searchbox
        box.image=UIImage(named: "dc")
        self.bringSubviewToFront(box)
        
       
        backTime.isHidden=true
        
        //  gesture tap
        let tap1=UITapGestureRecognizer.init(target: self, action: #selector(chooseAddressFrom))
        tap1.delegate=self
        address_from.addGestureRecognizer(tap1)
        
        let tap2=UITapGestureRecognizer.init(target: self, action: #selector(chooseAddressArrive))
        tap2.delegate=self
        address_to.addGestureRecognizer(tap2)
        
        let tap3=UITapGestureRecognizer.init(target: self, action: #selector(chooseTimeDepart))
        tap3.delegate=self
        goTime.addGestureRecognizer(tap3)
        
        
        //城市选择监听
        NotificationCenter.default.addObserver(self, selector: #selector(chooseDepartCity), name: NSNotification.Name(rawValue: "chooseDepart"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(chooseArriveCity), name: NSNotification.Name(rawValue: "chooseArrive"), object: nil)
        
        // 城市交换按钮
        let tap=UITapGestureRecognizer.init()
        tap.addTarget(self, action: #selector(changeAddress))
        exchangeImg.addGestureRecognizer(tap)
        
        kidBtn.setImage(UIImage(named: "保险-选中"), for: .selected)
        
    }
    
    
    
    
    
    // 注册重用Cell标识
       func jxBanner(_ banner: JXBannerType)
           -> (JXBannerCellRegister) {
               return JXBannerCellRegister(type: JXBannerCell.self,
               reuseIdentifier: "JXDefaultVCCell")
           }

       // 轮播总数
       func jxBanner(numberOfItems banner: JXBannerType)
       -> Int { return propData?.count ?? 0 }

       // 轮播cell内容设置
    func jxBanner(_ banner: JXBannerType,cellForItemAt index: Int,cell: UICollectionViewCell)-> UICollectionViewCell {
               let tempCell: JXBannerCell = cell as! JXBannerCell
               tempCell.layer.cornerRadius = 8
               tempCell.layer.masksToBounds = true
        let imgStr = propData?[index]["img"].string ?? ""
     
        tempCell.imageView.kf.setImage(with: URL(string: imgStr))
        
               return tempCell
           }

       // banner基本设置（可选）
       func jxBanner(_ banner: JXBannerType,layoutParams: JXBannerLayoutParams)-> JXBannerLayoutParams {
        
               return layoutParams
                .itemSize(CGSize(width: SCREEN_WIDTH, height: 209))
           }
    
    func jxBanner(_ banner: JXBannerType,
           params: JXBannerParams)
           -> JXBannerParams {
        
        return params.isAutoPlay(true).isPagingEnabled(true).timeInterval(2).isShowPageControl(false)
        
        }
    
    
    
    @objc func changeAddress(){
        transformAnimation(view: exchangeImg)
        
        let address=address_from.text
        address_from.text=address_to.text
        address_to.text=address
        
        let code=departCityCode
        departCityCode=arriveCityCode
        arriveCityCode=code
        
    }
    
    @objc func chooseDepartCity(sender:Notification){
        let dic=sender.object  as! Dictionary<String, Any>
        address_from.text=dic["cityName"] as? String
        departCityCode=dic["cityCode"] as? String ?? ""
    }
    
    @objc func chooseArriveCity(sender:Notification){
        let dic=sender.object  as! Dictionary<String, Any>
        address_to.text=dic["cityName"] as? String
        arriveCityCode=dic["cityCode"] as? String ?? ""

    }
    
    
    @objc func chooseAddressFrom(){
     
        let vc=SDCitySelectVC.init()
        getCurrentVc().present(vc, animated: true, completion: nil)
        
    }
    
    @objc func chooseAddressArrive(){
        let vc=SDCitySelectVC.init()
        vc.isDepart=false
        getCurrentVc().present(vc, animated: true, completion: nil)
    }
    
    @objc func chooseTimeDepart(){
        
        
        let dic = ["departDate":go_Time ?? "","departCityCode":departCityCode ,"arriveCityCode":arriveCityCode]
        
        
        Network.request(.searchPriceByday(dic)) { (JSON) in
            print("\(JSON)")
            if JSON["code"].int == 1 {
                guard let arr = JSONDeserializer<PriceCalendarModel>.deserializeModelArrayFrom(json: "\(JSON["data"])")else {
                    return
                }

                for model in arr{

                    self.calenArr.append(model as Any)
                }



                self.showCalendar()
            }
        } failure: { (err) in

        }

        
        

    }
    
    
    func showCalendar(){
        
            let vc=MSSCalendarViewController.init()
            vc.limitMonth = 2 ;// 显示几个月的日历
            vc.isDanCheng=true
            vc.type = MSSCalendarViewControllerType.nextType
            vc.beforeTodayCanTouch = false;// 今天之前的日期是否可以点击
            vc.afterTodayCanTouch = true;// 今天之后的日期是否可以点击
            vc.delegate = self
            vc.showPrice = true
           
             vc.priceArr = calenArr
            getCurrentVc().present(vc, animated: true, completion: nil)
        
    }
    
    func calendarViewConfirmClick(withStartDate startDate: Int, endDate: Int) {
        
        let mdateFormatter=DateFormatter.init()
        mdateFormatter.dateFormat="YYYY-MM-dd"
        go_Time=mdateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(startDate)))
        back_Time=mdateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(endDate)))
        
        let dateFormatter=DateFormatter.init()
        dateFormatter.dateFormat="MM月dd日"
        goTime.text = dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(startDate)))
       
        backTime.setTitle(dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(endDate))), for: .normal)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        5
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:BannerCollectionViewCell=collectionView.dequeueReusableCell(withReuseIdentifier: "BannerCollectionViewCell", for: indexPath) as! BannerCollectionViewCell
        cell.img.image=UIImage(named: "组4")
        self.bringSubviewToFront(box)

        return cell
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        let index = scrollView.contentOffset.x / scrollView.frame.size.width
        let showIndex = lroundf(Float(index))
      
        pageControl.currentPage = showIndex

    }
    
    @IBAction func search(_ sender: Any) {
        let vc=AirTicketDanSearchList.init()
        
        if childType == 1 {
            vc.sendDic=["departDate":go_Time ?? "","departCityCode":departCityCode ?? "","arriveCityCode":arriveCityCode ?? "","cabin":cabinArr,"childType":childType]
        }else{
            vc.sendDic=["departDate":go_Time ?? "","departCityCode":departCityCode ?? "","arriveCityCode":arriveCityCode ?? "","cabin":cabinArr]
        }
        
        vc.address1Code=departCityCode
        vc.address2Code=arriveCityCode
        vc.fromStr=address_from.text
        vc.toStr=address_to.text
        vc.dateStr=go_Time
        vc.hidesBottomBarWhenPushed=true
        getCurrentVc().navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func clickDanCheng(_ sender: Any) {
       
        backTime.isHidden=true
        box.image=UIImage(named: "dc")
        dcBtn.setTitleColor(UIColor.init(hexString: "3e86fa"), for: .normal)
        wfBtn.setTitleColor(UIColor.init(hexString: "ffffff"), for: .normal)

    }
    
    @IBAction func clickWangFan(_ sender: Any) {
        
        YProgressHUD.showToast("暂未开放")
       
//        backTime.isHidden=false
//        box.image=UIImage(named: "wf")
//        wfBtn.setTitleColor(UIColor.init(hexString: "3e86fa"), for: .normal)
//        dcBtn.setTitleColor(UIColor.init(hexString: "ffffff"), for: .normal)
    }
    
    @IBAction func kidTip(_ sender: Any) {
        let tipview=KidTicketTipVIew.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        getCurrentVc().view.addSubview(tipview)
        
    }
    
    
    @IBAction func chooseKid(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
        if sender.isSelected {
            childType=1
            
        }else{
            childType=0
        }
        
        
    }
    
    @IBAction func chooseBaby(_ sender: Any) {
        
        
        
    }
    
    
    @IBAction func chooseCangwei(_ sender: Any) {
        let view=CangweiPickview.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        view.propType={[weak self](arg0)  in
            
            self?.cangweiBtn.setTitle(arg0.1, for: .normal)
            if arg0.0 == 0 {
                self?.cabinArr=[1,2]
            }
            if arg0.0 == 1 {
                self?.cabinArr=[1]
            }
            if arg0.0 == 2 {
                self?.cabinArr=[2]
            }
            
        }
        getCurrentVc().view.addSubview(view)
    }
    
    
    
//    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
//
//        if touch.view?.superview?.classForCoder == Air_BannerCollectionCell().classForCoder {
//            return false
//        }
//    
//        return true
//    }
    
}
